package Threads;

import java.util.concurrent.locks.ReentrantLock;

public class test {
    public static void main(String[] args) {
        Consumer consumer = new Consumer();

        Thread thread1 = new Thread(consumer);
        Thread thread2 = new Thread(consumer);
        Thread thread3 = new Thread(consumer);

        thread1.start();
        thread2.start();
        thread3.start();

    }
}

class Consumer implements Runnable {

    private int count = 100;

    // 创建锁对象，所有线程共享一个锁对象
    private ReentrantLock lock = new ReentrantLock();

    public void run() {
        while (true) {
            try {
                lock.lock();
                if (count == 0)
                    break;

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + "消费了第" + count + "个商品");
                count--;
            } finally {
                lock.unlock();
            }
        }
    }

}
